package com.maixun.uitrasound.ad

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.launcher.ARouter
import com.maixun.lib_base.ui.fragment.BaseFragmentImpl
import com.maixun.lib_comment.ARouterConstance
import com.maixun.lib_comment.extends.loadPicture
import com.maixun.uitrasound.R
import com.maixun.uitrasound.entity.BannerBeen
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_ad.*
import java.util.concurrent.TimeUnit

/**
 * 作者：Lmoumou
 * 时间：2020/9/3 14:21
 */
class ADFragment : BaseFragmentImpl() {

    companion object {
        fun newInstance(bannerBeen: BannerBeen): Fragment = ADFragment().apply {
            val bundle = Bundle()
            bundle.putParcelable("bannerBeen", bannerBeen)
            arguments = bundle
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_ad

    override fun isLazyLoad(): Boolean = true

    override fun loadData() {

    }

    private lateinit var bannerBeen: BannerBeen

    override fun initView(rootView: View, savedInstanceState: Bundle?) {
        bannerBeen =
            arguments?.getParcelable<BannerBeen>("bannerBeen") ?: throw NullPointerException()

        mPathImageView.loadPicture(bannerBeen.url)

        tvSkip.setOnClickListener {
            toMain()
        }

        mPathImageView.setOnClickListener {
//            BannerHelper.onBannerClick(mContext, bannerBeen)
        }

        cutDown(5L)
    }

    private fun toMain() {
        d?.dispose()
        d = null
        ARouter.getInstance().build(ARouterConstance.APP.URL_MAIN).navigation()
        activity?.finish()
    }

    private var d: Disposable? = null

    @SuppressLint("SetTextI18n")
    private fun cutDown(delay: Long) {
        tvSkip.text = "${delay}s 跳过"
        d = Observable.interval(0, 1, TimeUnit.SECONDS).take(delay)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                val seconds = (delay - it).toInt()
                tvSkip.text = "${seconds}s 跳过"
                if (seconds == 1) {
                    toMain()
                }
            }
    }

    override fun onDestroy() {
        d?.dispose()
        d = null
        super.onDestroy()
    }
}